package com.caesar.gxmz;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.OnekeyShareTheme;

import com.caesar.gxmz.FragmentPage1.GetShareTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.webkit.GeolocationPermissions.Callback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;

public class FragmentPage5 extends Fragment {
	private LinearLayout rl_titile_bar_right;
	private SwipeRefreshLayout swipeLayout;
	private static String titleString = null;
	private static String summaryString = null;
	private static String imageString = null;
	private ProgressDialog progressDialog = null;
	private String startString = null;
	private WebView webView;
	private ImageView btnBack;
	private static String urlString = "http://web.fdcanet.com/index.php?app=agent&id=1111111119&act=media&appid=1";

	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				progressDialog.show();
				GetShareTask shareTask = new GetShareTask();
				shareTask.execute();
				break;
			case 2:

				break;
			case 3:

				break;
			}
		}
	};
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_5, null);
	}

	@SuppressLint("SetJavaScriptEnabled")
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		webView = (WebView) getActivity().findViewById(R.id.myWebView_05);
		progressDialog = new ProgressDialog(getActivity());
		progressDialog.setMessage("请耐心等待...");
		WebSettings wSet = webView.getSettings();
		wSet.setJavaScriptEnabled(true);
		String dirString = this.getActivity().getApplicationContext()
				.getDir("database", Context.MODE_PRIVATE).getPath();
		wSet.setGeolocationEnabled(true);
		wSet.setGeolocationDatabasePath(dirString);
		wSet.setJavaScriptCanOpenWindowsAutomatically(true);
		wSet.setAllowFileAccess(true);// 设置允许访问文件数据
		wSet.setSupportZoom(false);
		wSet.setBuiltInZoomControls(false);
		wSet.setJavaScriptCanOpenWindowsAutomatically(true);
		wSet.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
		wSet.setDomStorageEnabled(true);
		wSet.setDatabaseEnabled(true);

		wSet.setCacheMode(WebSettings.LOAD_DEFAULT);
		SharedPreferences sp = getActivity()
				.getSharedPreferences("MarrayNote",
						Activity.MODE_PRIVATE);
		String agent_id = sp.getString("agent_id", "7907924");
		startString="http://web.fdcanet.com/index.php?app=agent&id="+agent_id+"&act=media&appid=1";
		urlString=startString;
		Log.d("urlString", urlString);
		btnBack = (ImageView) getActivity().findViewById(
				R.id.btnBack5);
		btnBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (webView.canGoBack()) {
					webView.goBack();
				}
			}
		});
		webView.setWebChromeClient(new WebChromeClient() {

			@Override
			public void onReceivedIcon(WebView view, Bitmap icon) {
				// TODO Auto-generated method stub
				super.onReceivedIcon(view, icon);
			}

			@Override
			public void onGeolocationPermissionsShowPrompt(String origin,
					Callback callback) {
				callback.invoke(origin, true, false);
				super.onGeolocationPermissionsShowPrompt(origin, callback);
			}

		});

		webView.setWebViewClient(new WebViewClient() {
			public boolean shouldOverrideUrlLoading(WebView view, String url) { // 重写此方法表明点击网页里面的链接还是在当前的webview里跳转，不跳到浏览器那边
				if (url.contains("act=media")) {
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
					handler.sendEmptyMessage(1);
				}else if(url.equals(startString)){
					btnBack.setVisibility(View.INVISIBLE);
					urlString = url;
				}else{
					btnBack.setVisibility(View.VISIBLE);
					urlString = url;
				}
				view.loadUrl(url);
				return true;
			}
		});
		
		webView.loadUrl(urlString);
		swipeLayout = (SwipeRefreshLayout) getActivity().findViewById(
				R.id.swipe_container);
		swipeLayout
				.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

					@Override
					public void onRefresh() {
						// 重新刷新页面
						webView.loadUrl(urlString);
					}
				});
		rl_titile_bar_right = (LinearLayout) getActivity().findViewById(
				R.id.rl_titile_bar_right5);
		rl_titile_bar_right.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				showShare(getActivity(), null, false);

			}
		});

	}
	
	class GetShareTask extends AsyncTask<String, String, String> {
		private String jsonString = null;

		protected String doInBackground(String... param) {
			HttpGet request = new HttpGet(urlString + "&json=1");
			try {
				HttpResponse response = new DefaultHttpClient()
						.execute(request);
				if (response.getStatusLine().getStatusCode() != 404) {
					jsonString = EntityUtils.toString(response.getEntity());
				}
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (IllegalStateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return jsonString;
		}

		protected void onPostExecute(String result) {
			progressDialog.dismiss();
			if (result != null) {
				try {
					JSONObject loginObject = new JSONObject(result);
					JSONObject dataObject = loginObject.getJSONObject("data");
					titleString = dataObject.getString("title");
					summaryString = dataObject.getString("summary");
					imageString = dataObject.getString("image");
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}

	}
	
	/**
	 * 演示调用ShareSDK执行分享
	 * 
	 * @param context
	 * @param platformToShare
	 *            指定直接分享平台名称（一旦设置了平台名称，则九宫格将不会显示）
	 * @param showContentEdit
	 *            是否显示编辑页
	 */
	public static void showShare(Context context, String platformToShare,
			boolean showContentEdit) {
		OnekeyShare oks = new OnekeyShare();
		oks.setSilent(!showContentEdit);
		if (platformToShare != null) {
			oks.setPlatform(platformToShare);
		}
		// ShareSDK快捷分享提供两个界面第一个是九宫格 CLASSIC 第二个是SKYBLUE
		oks.setTheme(OnekeyShareTheme.CLASSIC);
		// 令编辑页面显示为Dialog模式
		oks.setDialogMode();
		// 在自动授权时可以禁用SSO方式
		oks.disableSSOWhenAuthorize();
		// oks.setAddress("12345678901"); //分享短信的号码和邮件的地址
		if (titleString == null) {
			titleString = "Real Estate Agent - media";
		}
		if (summaryString == null) {
			summaryString = "Tyloon Media Corporation in February 25, 2015 the formal launch ofreal estate agents mobile phone network, will provide American realestate network powerful search function for all ordering mobile phonereal estate network service estate agent.";
		}
		if (imageString == null) {
			imageString = "http://web.fdcanet.com/data/files/mall/portrait/1/31.jpg";
		}
		oks.setTitle(titleString);
		oks.setTitleUrl(urlString);
		oks.setText(summaryString+" "+urlString);
		// oks.setImagePath("/sdcard/test-pic.jpg"); //分享sdcard目录下的图片
		oks.setImageUrl(imageString);
		oks.setUrl(urlString); // 微信不绕过审核分享链接
		// oks.setFilePath("/sdcard/test-pic.jpg");
		// //filePath是待分享应用程序的本地路劲，仅在微信（易信）好友和Dropbox中使用，否则可以不提供
		oks.setComment(summaryString); // 我对这条分享的评论，仅在人人网和QQ空间使用，否则可以不提供
		oks.setSite(titleString); // QZone分享完之后返回应用时提示框上显示的名称
		oks.setSiteUrl(urlString);// QZone分享参数
		oks.setVenueName(titleString);
		oks.setVenueDescription(imageString);
		// 将快捷分享的操作结果将通过OneKeyShareCallback回调
		// oks.setCallback(new OneKeyShareCallback());
		// 去自定义不同平台的字段内容
		// oks.setShareContentCustomizeCallback(new
		// ShareContentCustomizeDemo());
		// 在九宫格设置自定义的图标
		Bitmap logo = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.ic_launcher);
		String label = "易美居";
		OnClickListener listener = new OnClickListener() {
			public void onClick(View v) {

			}
		};
		oks.setCustomerLogo(logo, label, listener);

		// 为EditPage设置一个背景的View
		// oks.setEditPageBackground(getPage());
		// 隐藏九宫格中的新浪微博
		// oks.addHiddenPlatform(SinaWeibo.NAME);

		// String[] AVATARS = {
		// "http://99touxiang.com/public/upload/nvsheng/125/27-011820_433.jpg",
		// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339485237265.jpg",
		// "http://diy.qqjay.com/u/files/2012/0523/f466c38e1c6c99ee2d6cd7746207a97a.jpg",
		// "http://diy.qqjay.com/u2/2013/0422/fadc08459b1ef5fc1ea6b5b8d22e44b4.jpg",
		// "http://img1.2345.com/duoteimg/qqTxImg/2012/04/09/13339510584349.jpg",
		// "http://diy.qqjay.com/u2/2013/0401/4355c29b30d295b26da6f242a65bcaad.jpg"
		// };
		// oks.setImageArray(AVATARS); //腾讯微博和twitter用此方法分享多张图片，其他平台不可以

		// 启动分享
		oks.show(context);
	}
	
	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		final AlertDialog.Builder normalDialog = 
	            new AlertDialog.Builder(getActivity());
	        normalDialog.setTitle("用户操作提示");
	        normalDialog.setMessage("您确认需要退出?");
	        normalDialog.setPositiveButton("确定", 
	            new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	            	SharedPreferences sp = getActivity()
							.getSharedPreferences("MarrayNote",
									Activity.MODE_PRIVATE);
					Editor edit = sp.edit();
					edit.putBoolean("userLogin", false);
					edit.commit();
					Intent intent = new Intent(getActivity(),
							WelcomeActivity.class);
					startActivity(intent);
					getActivity().finish();
	            }
	        });
	        normalDialog.setNegativeButton("关闭", 
	            new DialogInterface.OnClickListener() {
	            @Override
	            public void onClick(DialogInterface dialog, int which) {
	                //...To-do
	            }
	        });
	        // 显示
	        normalDialog.show();
	}

}